const http = require('http')
const fs = require('fs')
const path = require('path')
const url = require('url')
const common = require('./module/common')

http.createServer(function(req, res) {

  // 1. 获取地址
  let pathname = url.parse(req.url).pathname; // 去掉 search后缀

  pathname = pathname === '/' ? '/index.html':pathname

  // 可以获取后缀名 path.extname()
  let extname = path.extname(pathname)

  // 2. 通过fs模块读取文件
  if(pathname !== '/favicon.ico') {
    fs.readFile('./static' + pathname, async (err,data) => {
      if(err) {
        console.log(err)
        res.writeHead(404, {'Content-Type': 'text/html;charset=utf-8'})
        res.end('这个页面不存在')
        return;
      }
      let mime = await common.getFileMime(extname)
      res.writeHead(200, {'Content-Type': mime +';charset=utf-8'})
      res.end(data)
    })
  }
}).listen(8081)
